<template>
  <base-modal :title="title" :show.sync="visible" width="900px">
    <div class="content">
      <div class="search-box">
        <el-input
          v-model="keyword"
          prefix-icon="el-icon-search"
          :placeholder="$t('product.placeholder.keyword')"
          @input="handleSearch"
          clearable
        ></el-input>
      </div>

      <div class="table-box">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          style="width: 100%"
          header-row-class-name="common-list-table-header__v2"
          max-height="500"
          border
          ref="tableRef"
          :row-key="getRowKeys"
          @select="handleSelectionChange"
          @select-all="handleSelectionChange"
          :tree-props="{children: 'inventedChildren', hasChildren: 'hasInventedChildren'}"
        >
          <!-- 需求如此：只展示一级 不展示子级 inventedChildren是不存在的-->
          <el-table-column
            type="selection"
            width="55"
            :reserve-selection="true"
          >
          </el-table-column>
          <el-table-column
            v-for="(item, index) in columns"
            :key="`${item.displayName}_${index}`"
            :prop="item.fieldName"
            :label="item.displayName"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <!-- 状态 -->
              <template v-if="item.fieldName === 'materialStatus'">
                {{ scope.row.materialStatus ? $t('common.base.open') : $t('common.base.disable') }}
              </template>
              <template v-else>
                {{
                  $formatFormField(item, scope.row)
                }}
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagping-box">
        <el-pagination
          class="base-pagination"
          :background="true"
          layout="total, prev, pager, next"
          :total="total"
          :page-size="listQueryPage.pageSize"
          :current-page="listQueryPage.pageNum"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>

    <div slot="footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="handleClickSubmit"
        >{{$t('common.modal.MODIFY')}}</el-button
      >
    </div>
  </base-modal>
</template>
<script>
import Platform from '@src/util/platform.ts';
import { getMaterielPage } from '@src/api/ProductV2Api';
import _ from 'lodash';

export default {
  name: 'material-dialog',
  props: {
    columns: {
      type: Array,
      default: () => [],
    },
    catalogId: {
      type: String,
      default: ''
    },
    dataList: {
      type: Array,
      default: () => [],
    },
    pageType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      listLoading: false,
      keyword: '',
      tableData: [],
      total: 0,
      listQueryPage: {
        pageNum: 1,
        pageSize: 10,
      },
      multipleSelection: [],
    };
  },
  computed: {
    // 标题
    title() {
      return this.$t('task.edit.addMaterial');
    },
    listIds() {
      return (this.dataList || []).map(item => item.id)
    }
  },
  methods: {
    // 获取物料列表数据
    fetchMaterialList() {
      const params = {
        keyword: this.keyword,
        ...this.listQueryPage,
        catalogId: this.catalogId || '',
        excludeCatalogId: this.catalogId || '',
        excludeIds: this.listIds,
        bomMaterialFlag: true // 为true根据BOM查物料的结构层级
      };
      
      // 编辑时只查询两级
      if(this.pageType === 'edit') {
        params.maxLevel = 2;
      }

      this.listLoading = true;
      
      getMaterielPage(params)
        .then(res => {
          const { success, data } = res;

          if (!success) return Platform.toast(res.message, 'error');

          this.tableData = data.list || [];

          this.total = data.total || 0;
        })
        .finally(() => {
          this.listLoading = false;
        })
        .catch(err => {
          console.error('err', err);
        });
    },
    // 重置数据
    resetList() {
      this.multipleSelection = [];
      this.keyword = '';
      this.listQueryPage = {
        pageNum: 1,
        pageSize: 10,
      };
    },
    // 打开添加弹框
    openMaterialList() {
      this.visible = true;
      this.$refs.tableRef.clearSelection();
      this.resetList();
      this.fetchMaterialList();
    },
    // 搜素
    handleSearch: _.debounce(function () {
      this.listQueryPage.pageNum = 1;
      this.fetchMaterialList();
    }, 500),
    // 切换分页
    handleCurrentChange(val) {
      this.listQueryPage.pageNum = val;
      this.fetchMaterialList();
    },
    getRowKeys(row) {
      // 不需要展示子集
      return row.id;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => {
        return {
          ...item,
          num: item.num || 1,
        };
      });
    },
    handleClickSubmit() {
      if (!this.multipleSelection.length) {
        return Platform.toast(this.$t('product.tips.minSelectTip'), 'warning')
      }
      this.visible = false;
      this.$emit('handleSubmit', this.multipleSelection);
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  padding: 24px;

  .search-box {
    display: flex;
    justify-content: flex-end;
    ::v-deep .el-input {
      width: 300px;
    }
    ::v-deep .el-input__inner {
      border: 1px solid #e0e1e2 !important;
    }
    ::v-deep .el-input__inner:focus {
      outline: none;
      border-color: $color-primary-light-6 !important;
    }
  }

  .table-box {
    margin: 10px 0;
    ::v-deep .el-table {
      border-top: 1px solid #e8e8e8;
      border-left: 1px solid #e8e8e8;
    }
  }

  .base-pagination {
    border: none;
  }
}
</style>